import type { KnowledgeDetail } from '@/types/knowledge';

/**
 * 设计模式知识点数据
 */
export const patternKnowledge : KnowledgeDetail[] = [
	{
		id: 31,
		title: '单例模式',
		description: '最常用的设计模式，饿汉式、懒汉式、双重检查锁等实现方式，确保类只有一个实例。',
		icon: '🎯',
		categoryId: 'pattern',
		categoryName: '设计模式',
		categoryIcon: '🎨',
		difficulty: '进阶',
		color: 'linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%)',
		headerBg: 'linear-gradient(135deg, #2c3e50 0%, #34495e 100%)',
		tagBg: 'linear-gradient(135deg, #16a085 0%, #1abc9c 100%)',
		tagColor: '#ffffff',
		difficultyBg: 'linear-gradient(135deg, #e74c3c 0%, #c0392b 100%)',
		keyPoints: [
			{
				point: '饿汉式：类加载时创建实例，线程安全但可能浪费内存。',
				code: `public class EagerSingleton {
    // 类加载时就创建实例
    private static final EagerSingleton INSTANCE = new EagerSingleton();
    
    // 私有构造函数，防止外部创建实例
    private EagerSingleton() {
        System.out.println("EagerSingleton实例被创建");
    }
    
    // 提供全局访问点
    public static EagerSingleton getInstance() {
        return INSTANCE;
    }
    
    public void doSomething() {
        System.out.println("执行业务逻辑");
    }
}

// 使用示例
public class Test {
    public static void main(String[] args) {
        EagerSingleton s1 = EagerSingleton.getInstance();
        EagerSingleton s2 = EagerSingleton.getInstance();
        System.out.println(s1 == s2);  // true，同一个实例
    }
}`
			},
			{
				point: '懒汉式（线程不安全）：第一次使用时创建实例，节省内存但有线程安全问题。',
				code: `public class LazySingleton {
    private static LazySingleton instance;
    
    private LazySingleton() {}
    
    // ❌ 线程不安全的懒汉式
    public static LazySingleton getInstance() {
        if (instance == null) {
            // 多线程环境下，可能创建多个实例
            instance = new LazySingleton();
        }
        return instance;
    }
}

// ✅ 线程安全的懒汉式（synchronized）
public class SafeLazySingleton {
    private static SafeLazySingleton instance;
    
    private SafeLazySingleton() {}
    
    // synchronized保证线程安全，但性能较差
    public static synchronized SafeLazySingleton getInstance() {
        if (instance == null) {
            instance = new SafeLazySingleton();
        }
        return instance;
    }
}`
			},
			{
				point: '双重检查锁（DCL）：线程安全的懒汉式，使用volatile防止指令重排序，性能好。',
				code: `public class DoubleCheckedSingleton {
    // volatile 防止指令重排序
    private static volatile DoubleCheckedSingleton instance;
    
    private DoubleCheckedSingleton() {}
    
    public static DoubleCheckedSingleton getInstance() {
        // 第一次检查：避免不必要的同步
        if (instance == null) {
            synchronized (DoubleCheckedSingleton.class) {
                // 第二次检查：防止多个线程同时进入synchronized块
                if (instance == null) {
                    instance = new DoubleCheckedSingleton();
                }
            }
        }
        return instance;
    }
}

// 为什么需要volatile？
/*
instance = new DoubleCheckedSingleton() 不是原子操作：
1. 分配内存空间
2. 初始化对象
3. 将instance指向内存地址

指令重排序可能导致：1 -> 3 -> 2
线程A执行到3时，线程B看到instance != null，但对象未初始化
*/`
			},
			{
				point: '静态内部类：推荐实现方式，利用类加载机制保证线程安全，延迟加载。',
				code: `public class StaticInnerSingleton {
    // 私有构造函数
    private StaticInnerSingleton() {}
    
    // 静态内部类，只有在调用getInstance()时才会加载
    private static class SingletonHolder {
        private static final StaticInnerSingleton INSTANCE = new StaticInnerSingleton();
    }
    
    public static StaticInnerSingleton getInstance() {
        return SingletonHolder.INSTANCE;
    }
}

/*
优点：
1. 延迟加载：只有调用getInstance()时才创建实例
2. 线程安全：类加载机制保证线程安全
3. 性能好：无需synchronized
4. 推荐使用！
*/`
			},
			{
				point: '枚举单例：最简洁、最安全的实现，自动支持序列化，防止反射攻击。',
				code: `// 最简洁的单例实现
public enum EnumSingleton {
    INSTANCE;
    
    private String data;
    
    public void setData(String data) {
        this.data = data;
    }
    
    public String getData() {
        return data;
    }
    
    public void doSomething() {
        System.out.println("执行业务逻辑: " + data);
    }
}

// 使用示例
public class Test {
    public static void main(String[] args) {
        EnumSingleton singleton = EnumSingleton.INSTANCE;
        singleton.setData("Hello");
        singleton.doSomething();
        
        // 多线程测试
        Thread t1 = new Thread(() -> {
            System.out.println(EnumSingleton.INSTANCE.hashCode());
        });
        Thread t2 = new Thread(() -> {
            System.out.println(EnumSingleton.INSTANCE.hashCode());
        });
        t1.start();
        t2.start();
        // 输出相同的hashCode
    }
}

/*
优点：
1. 代码简洁
2. 线程安全（枚举本身保证）
3. 自动支持序列化
4. 防止反射攻击（枚举不能通过反射创建）
5. 《Effective Java》作者推荐！
*/`
			}
		]
	},
	{
		id: 32,
		title: '工厂模式',
		description: '创建型模式，简单工厂、工厂方法、抽象工厂，解耦对象创建，提高代码灵活性。',
		icon: '🏭',
		categoryId: 'pattern',
		categoryName: '设计模式',
		categoryIcon: '🎨',
		difficulty: '进阶',
		color: 'linear-gradient(135deg, #ff9a9e 0%, #fad0c4 100%)',
		headerBg: 'linear-gradient(135deg, #2c3e50 0%, #34495e 100%)',
		tagBg: 'linear-gradient(135deg, #16a085 0%, #1abc9c 100%)',
		tagColor: '#ffffff',
		difficultyBg: 'linear-gradient(135deg, #e74c3c 0%, #c0392b 100%)',
		keyPoints: [
			{
				point: '简单工厂：一个工厂类根据参数创建不同的产品对象，违背开闭原则但简单实用。',
				code: `// 产品接口
interface Product {
    void use();
}

// 具体产品
class ProductA implements Product {
    @Override
    public void use() {
        System.out.println("使用产品A");
    }
}

class ProductB implements Product {
    @Override
    public void use() {
        System.out.println("使用产品B");
    }
}

// 简单工厂类
public class SimpleFactory {
    public static Product createProduct(String type) {
        if ("A".equals(type)) {
            return new ProductA();
        } else if ("B".equals(type)) {
            return new ProductB();
        }
        throw new IllegalArgumentException("未知的产品类型");
    }
}

// 使用示例
public class Test {
    public static void main(String[] args) {
        Product productA = SimpleFactory.createProduct("A");
        productA.use();  // 使用产品A
        
        Product productB = SimpleFactory.createProduct("B");
        productB.use();  // 使用产品B
    }
}`
			},
			{
				point: '工厂方法模式：定义创建对象的接口，让子类决定实例化哪个类，符合开闭原则。',
				code: `// 产品接口
interface Product {
    void use();
}

// 具体产品
class ConcreteProductA implements Product {
    @Override
    public void use() {
        System.out.println("使用产品A");
    }
}

class ConcreteProductB implements Product {
    @Override
    public void use() {
        System.out.println("使用产品B");
    }
}

// 工厂接口
interface Factory {
    Product createProduct();
}

// 具体工厂
class FactoryA implements Factory {
    @Override
    public Product createProduct() {
        return new ConcreteProductA();
    }
}

class FactoryB implements Factory {
    @Override
    public Product createProduct() {
        return new ConcreteProductB();
    }
}

// 使用示例
public class Test {
    public static void main(String[] args) {
        // 创建工厂A
        Factory factoryA = new FactoryA();
        Product productA = factoryA.createProduct();
        productA.use();
        
        // 创建工厂B
        Factory factoryB = new FactoryB();
        Product productB = factoryB.createProduct();
        productB.use();
        
        // 新增产品C，只需增加ProductC和FactoryC，无需修改现有代码
    }
}`
			},
			{
				point: '抽象工厂模式：提供创建一系列相关或相互依赖对象的接口，无需指定具体类。',
				code: `// 抽象产品族
interface Button {
    void click();
}

interface TextField {
    void input();
}

// Windows风格产品
class WindowsButton implements Button {
    @Override
    public void click() {
        System.out.println("Windows按钮被点击");
    }
}

class WindowsTextField implements TextField {
    @Override
    public void input() {
        System.out.println("Windows文本框输入");
    }
}

// Mac风格产品
class MacButton implements Button {
    @Override
    public void click() {
        System.out.println("Mac按钮被点击");
    }
}

class MacTextField implements TextField {
    @Override
    public void input() {
        System.out.println("Mac文本框输入");
    }
}

// 抽象工厂接口
interface GUIFactory {
    Button createButton();
    TextField createTextField();
}

// 具体工厂
class WindowsFactory implements GUIFactory {
    @Override
    public Button createButton() {
        return new WindowsButton();
    }
    
    @Override
    public TextField createTextField() {
        return new WindowsTextField();
    }
}

class MacFactory implements GUIFactory {
    @Override
    public Button createButton() {
        return new MacButton();
    }
    
    @Override
    public TextField createTextField() {
        return new MacTextField();
    }
}

// 使用示例
public class Application {
    private Button button;
    private TextField textField;
    
    public Application(GUIFactory factory) {
        button = factory.createButton();
        textField = factory.createTextField();
    }
    
    public void render() {
        button.click();
        textField.input();
    }
    
    public static void main(String[] args) {
        // 根据系统选择工厂
        String os = System.getProperty("os.name");
        GUIFactory factory;
        if (os.contains("Windows")) {
            factory = new WindowsFactory();
        } else {
            factory = new MacFactory();
        }
        
        Application app = new Application(factory);
        app.render();
    }
}`
			},
			{
				point: '开闭原则：工厂模式对扩展开放，对修改关闭，新增产品不影响现有代码。',
				code: `// 遵循开闭原则的工厂方法示例

// 1. 产品接口
interface PaymentMethod {
    void pay(double amount);
}

// 2. 具体产品
class AlipayPayment implements PaymentMethod {
    @Override
    public void pay(double amount) {
        System.out.println("支付宝支付: " + amount);
    }
}

class WeChatPayment implements PaymentMethod {
    @Override
    public void pay(double amount) {
        System.out.println("微信支付: " + amount);
    }
}

// 3. 工厂接口
interface PaymentFactory {
    PaymentMethod createPayment();
}

// 4. 具体工厂
class AlipayFactory implements PaymentFactory {
    @Override
    public PaymentMethod createPayment() {
        return new AlipayPayment();
    }
}

class WeChatFactory implements PaymentFactory {
    @Override
    public PaymentMethod createPayment() {
        return new WeChatPayment();
    }
}

// 5. 新增银联支付（不修改现有代码）
class UnionPayPayment implements PaymentMethod {
    @Override
    public void pay(double amount) {
        System.out.println("银联支付: " + amount);
    }
}

class UnionPayFactory implements PaymentFactory {
    @Override
    public PaymentMethod createPayment() {
        return new UnionPayPayment();
    }
}

// 使用
public class PaymentService {
    private PaymentFactory factory;
    
    public void setFactory(PaymentFactory factory) {
        this.factory = factory;
    }
    
    public void processPayment(double amount) {
        PaymentMethod payment = factory.createPayment();
        payment.pay(amount);
    }
}`
			},
			{
				point: '依赖倒置原则：高层模块不依赖低层模块，都依赖抽象，工厂返回接口类型。',
				code: `// 依赖倒置原则示例

// ❌ 不好的设计：高层依赖具体实现
class BadOrderService {
    private MySQLDatabase db = new MySQLDatabase();  // 依赖具体类
    
    public void saveOrder(Order order) {
        db.save(order);
    }
}

// ✅ 好的设计：依赖抽象
interface Database {
    void save(Object data);
    Object query(String sql);
}

class MySQLDatabase implements Database {
    @Override
    public void save(Object data) {
        System.out.println("MySQL保存数据");
    }
    
    @Override
    public Object query(String sql) {
        return null;
    }
}

class OracleDatabase implements Database {
    @Override
    public void save(Object data) {
        System.out.println("Oracle保存数据");
    }
    
    @Override
    public Object query(String sql) {
        return null;
    }
}

// 工厂接口
interface DatabaseFactory {
    Database createDatabase();
}

// 具体工厂
class MySQLFactory implements DatabaseFactory {
    @Override
    public Database createDatabase() {
        return new MySQLDatabase();
    }
}

class OracleFactory implements DatabaseFactory {
    @Override
    public Database createDatabase() {
        return new OracleDatabase();
    }
}

// 高层模块依赖抽象
class OrderService {
    private Database db;
    
    public OrderService(DatabaseFactory factory) {
        this.db = factory.createDatabase();  // 依赖抽象
    }
    
    public void saveOrder(Order order) {
        db.save(order);
    }
}

// 使用
public class Test {
    public static void main(String[] args) {
        // 切换数据库只需更换工厂，无需修改OrderService
        DatabaseFactory factory = new MySQLFactory();
        OrderService service = new OrderService(factory);
        service.saveOrder(new Order());
    }
}`
			}
		]
	},
	{
		id: 33,
		title: '代理模式',
		description: '静态代理、动态代理（JDK、CGLIB），Spring AOP的基础，控制对象的访问。',
		icon: '🎭',
		categoryId: 'pattern',
		categoryName: '设计模式',
		categoryIcon: '🎨',
		difficulty: '进阶',
		color: 'linear-gradient(135deg, #fbc2eb 0%, #a6c1ee 100%)',
		headerBg: 'linear-gradient(135deg, #2c3e50 0%, #34495e 100%)',
		tagBg: 'linear-gradient(135deg, #16a085 0%, #1abc9c 100%)',
		tagColor: '#ffffff',
		difficultyBg: 'linear-gradient(135deg, #e74c3c 0%, #c0392b 100%)',
		keyPoints: [
			{
				point: '静态代理：编译期确定代理类，代理类与目标类实现相同接口，手动编写代理逻辑。',
				code: `// 服务接口
interface UserService {
    void save(String user);
    String query(int id);
}

// 真实服务类
class UserServiceImpl implements UserService {
    @Override
    public void save(String user) {
        System.out.println("保存用户: " + user);
    }
    
    @Override
    public String query(int id) {
        System.out.println("查询用户: " + id);
        return "User" + id;
    }
}

// 静态代理类
class UserServiceProxy implements UserService {
    private UserService target;
    
    public UserServiceProxy(UserService target) {
        this.target = target;
    }
    
    @Override
    public void save(String user) {
        System.out.println("[代理] 开始事务");
        long start = System.currentTimeMillis();
        
        target.save(user);
        
        long time = System.currentTimeMillis() - start;
        System.out.println("[代理] 提交事务，耗时: " + time + "ms");
    }
    
    @Override
    public String query(int id) {
        System.out.println("[代理] 权限校验");
        String result = target.query(id);
        System.out.println("[代理] 记录日志");
        return result;
    }
}

// 使用
public class Test {
    public static void main(String[] args) {
        UserService service = new UserServiceImpl();
        UserService proxy = new UserServiceProxy(service);
        
        proxy.save("张三");
        proxy.query(1);
    }
}`
			},
			{
				point: 'JDK动态代理：基于接口，运行时动态生成代理类，使用Proxy和InvocationHandler实现。',
				code: `import java.lang.reflect.*;

// 服务接口
interface OrderService {
    void createOrder(String order);
    String getOrder(int id);
}

// 真实服务
class OrderServiceImpl implements OrderService {
    @Override
    public void createOrder(String order) {
        System.out.println("创建订单: " + order);
    }
    
    @Override
    public String getOrder(int id) {
        return "Order-" + id;
    }
}

// 动态代理处理器
class DynamicProxyHandler implements InvocationHandler {
    private Object target;
    
    public DynamicProxyHandler(Object target) {
        this.target = target;
    }
    
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) 
            throws Throwable {
        System.out.println("[代理] 方法调用前: " + method.getName());
        long start = System.currentTimeMillis();
        
        // 调用目标方法
        Object result = method.invoke(target, args);
        
        long time = System.currentTimeMillis() - start;
        System.out.println("[代理] 方法调用后，耗时: " + time + "ms");
        
        return result;
    }
}

// 使用
public class JDKProxyDemo {
    public static void main(String[] args) {
        OrderService realService = new OrderServiceImpl();
        
        // 创建代理对象
        OrderService proxy = (OrderService) Proxy.newProxyInstance(
            OrderService.class.getClassLoader(),
            new Class[]{OrderService.class},
            new DynamicProxyHandler(realService)
        );
        
        proxy.createOrder("订单1");
        String order = proxy.getOrder(123);
        System.out.println(order);
    }
}`
			},
			{
				point: 'CGLIB动态代理：基于继承，可以代理没有接口的类，使用字节码技术生成子类。',
				code: `import net.sf.cglib.proxy.*;

// 没有接口的类
class ProductService {
    public void addProduct(String name) {
        System.out.println("添加商品: " + name);
    }
    
    public String getProduct(int id) {
        return "Product-" + id;
    }
}

// CGLIB方法拦截器
class CglibMethodInterceptor implements MethodInterceptor {
    @Override
    public Object intercept(Object obj, Method method, Object[] args, 
                           MethodProxy proxy) throws Throwable {
        System.out.println("[CGLIB代理] 方法调用前: " + method.getName());
        
        // 调用父类方法
        Object result = proxy.invokeSuper(obj, args);
        
        System.out.println("[CGLIB代理] 方法调用后");
        return result;
    }
}

// 使用
public class CglibProxyDemo {
    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(ProductService.class);
        enhancer.setCallback(new CglibMethodInterceptor());
        
        ProductService proxy = (ProductService) enhancer.create();
        proxy.addProduct("手机");
        proxy.getProduct(1);
    }
}

// JDK代理 vs CGLIB代理：
/*
JDK动态代理：
- 只能代理实现了接口的类
- 基于反射机制
- 性能较好

CGLIB代理：
- 可以代理没有接口的类
- 基于字节码生成子类
- final方法无法代理
- 性能略差（但可以缓存）
*/`
			},
			{
				point: '代理模式的应用场景：远程代理、虚拟代理、保护代理、缓存代理、日志代理、事务代理等。',
				code: `// 1. 缓存代理
class CacheProxy implements UserService {
    private UserService target = new UserServiceImpl();
    private Map<Integer, String> cache = new HashMap<>();
    
    @Override
    public void save(String user) {
        target.save(user);
    }
    
    @Override
    public String query(int id) {
        if (cache.containsKey(id)) {
            System.out.println("[缓存代理] 从缓存获取");
            return cache.get(id);
        }
        
        String result = target.query(id);
        cache.put(id, result);
        return result;
    }
}

// 2. 延迟加载代理（虚拟代理）
class LazyLoadProxy {
    private HeavyObject realObject;
    
    public void doSomething() {
        if (realObject == null) {
            System.out.println("[虚拟代理] 延迟创建对象");
            realObject = new HeavyObject();  // 延迟加载
        }
        realObject.doSomething();
    }
}

// 3. 权限代理（保护代理）
class ProtectionProxy implements UserService {
    private UserService target = new UserServiceImpl();
    private String currentUser;
    
    public ProtectionProxy(String currentUser) {
        this.currentUser = currentUser;
    }
    
    @Override
    public void save(String user) {
        if (!"admin".equals(currentUser)) {
            throw new SecurityException("无权限");
        }
        target.save(user);
    }
    
    @Override
    public String query(int id) {
        return target.query(id);  // 所有人都可以查询
    }
}

// 使用
public class ProxyPatternDemo {
    public static void main(String[] args) {
        // 缓存代理
        UserService cacheProxy = new CacheProxy();
        cacheProxy.query(1);  // 查询数据库
        cacheProxy.query(1);  // 从缓存获取
        
        // 权限代理
        UserService adminProxy = new ProtectionProxy("admin");
        adminProxy.save("user1");  // 成功
        
        UserService guestProxy = new ProtectionProxy("guest");
        // guestProxy.save("user2");  // 抛出SecurityException
    }
}`
			},
			{
				point: 'Spring AOP基于代理模式实现，默认使用JDK代理或CGLIB代理，实现横切关注点的分离。',
				code: `import org.springframework.stereotype.Component;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.ProceedingJoinPoint;

// 业务服务
@Component
public class PaymentService {
    public void pay(String user, double amount) {
        System.out.println(user + " 支付 " + amount + " 元");
    }
}

// AOP切面
@Aspect
@Component
public class LoggingAspect {
    // 前置通知
    @Before("execution(* com.example..*.pay(..))")
    public void beforePay(JoinPoint joinPoint) {
        System.out.println("[AOP] 支付前检查");
    }
    
    // 后置通知
    @After("execution(* com.example..*.pay(..))")
    public void afterPay() {
        System.out.println("[AOP] 支付后记录");
    }
    
    // 环绕通知
    @Around("execution(* com.example..*.pay(..))")
    public Object aroundPay(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("[AOP] 环绕前");
        long start = System.currentTimeMillis();
        
        Object result = joinPoint.proceed();  // 执行目标方法
        
        long time = System.currentTimeMillis() - start;
        System.out.println("[AOP] 环绕后，耗时: " + time + "ms");
        return result;
    }
}

// 配置类
@Configuration
@EnableAspectJAutoProxy  // 启用AOP
@ComponentScan("com.example")
public class AppConfig {
}

// Spring AOP原理：
/*
1. Spring扫描@Aspect注解的类
2. 为目标bean创建代理对象
3. 有接口：使用JDK动态代理
4. 无接口：使用CGLIB代理
5. 调用方法时，代理拦截并执行切面逻辑
*/`
			}
		]
	},
	{
		id: 34,
		title: '观察者模式',
		description: '定义对象间一对多的依赖关系，当一个对象状态改变时通知所有依赖者，实现松耦合。',
		icon: '👀',
		categoryId: 'pattern',
		categoryName: '设计模式',
		categoryIcon: '🎨',
		difficulty: '进阶',
		color: 'linear-gradient(135deg, #a1c4fd 0%, #c2e9fb 100%)',
		headerBg: 'linear-gradient(135deg, #2c3e50 0%, #34495e 100%)',
		tagBg: 'linear-gradient(135deg, #16a085 0%, #1abc9c 100%)',
		tagColor: '#ffffff',
		difficultyBg: 'linear-gradient(135deg, #e74c3c 0%, #c0392b 100%)',
		keyPoints: [
			{
				point: '观察者模式：主题(Subject)维护观察者列表，状态改变时自动通知所有观察者。',
				code: `import java.util.*;

// 观察者接口
interface Observer {
    void update(String message);
}

// 主题接口
interface Subject {
    void attach(Observer observer);
    void detach(Observer observer);
    void notifyObservers();
}

// 具体主题（微信公众号）
class WeChatPublicAccount implements Subject {
    private List<Observer> observers = new ArrayList<>();
    private String article;
    
    @Override
    public void attach(Observer observer) {
        observers.add(observer);
        System.out.println("新增订阅者");
    }
    
    @Override
    public void detach(Observer observer) {
        observers.remove(observer);
        System.out.println("取消订阅");
    }
    
    @Override
    public void notifyObservers() {
        for (Observer observer : observers) {
            observer.update(article);
        }
    }
    
    public void publishArticle(String article) {
        this.article = article;
        System.out.println("发布新文章: " + article);
        notifyObservers();
    }
}

// 具体观察者（用户）
class User implements Observer {
    private String name;
    
    public User(String name) {
        this.name = name;
    }
    
    @Override
    public void update(String article) {
        System.out.println(name + " 收到推送: " + article);
    }
}

// 使用
public class ObserverDemo {
    public static void main(String[] args) {
        WeChatPublicAccount account = new WeChatPublicAccount();
        
        User user1 = new User("张三");
        User user2 = new User("李四");
        
        account.attach(user1);
        account.attach(user2);
        
        account.publishArticle("设计模式详解");
        // 输出：张三和李四都收到推送
    }
}`
			},
			{
				point: 'Java内置Observable和Observer：JDK提供的观察者模式实现（已过时，建议自己实现）。',
				code: `import java.util.Observable;
import java.util.Observer;

// 被观察者（JDK内置）
class StockMarket extends Observable {
    private double price;
    
    public void setPrice(double price) {
        this.price = price;
        setChanged();  // 标记状态已改变
        notifyObservers(price);  // 通知观察者
    }
    
    public double getPrice() {
        return price;
    }
}

// 观察者
class StockInvestor implements Observer {
    private String name;
    
    public StockInvestor(String name) {
        this.name = name;
    }
    
    @Override
    public void update(Observable o, Object arg) {
        double price = (Double) arg;
        System.out.println(name + " 收到股价变动通知: " + price);
    }
}

// 使用
public class JavaObserverDemo {
    public static void main(String[] args) {
        StockMarket market = new StockMarket();
        
        market.addObserver(new StockInvestor("投资者A"));
        market.addObserver(new StockInvestor("投资者B"));
        
        market.setPrice(100.5);
        market.setPrice(102.3);
    }
}

// 注意：Observable和Observer在Java 9后被标记为@Deprecated`
			},
			{
				point: '事件监听器模式：观察者模式在GUI和Spring中的应用，事件源+事件+监听器。',
				code: `import java.util.*;

// 事件对象
class OrderEvent extends EventObject {
    private String orderNo;
    
    public OrderEvent(Object source, String orderNo) {
        super(source);
        this.orderNo = orderNo;
    }
    
    public String getOrderNo() {
        return orderNo;
    }
}

// 事件监听器接口
interface OrderListener extends EventListener {
    void onOrderCreated(OrderEvent event);
}

// 事件源
class OrderService {
    private List<OrderListener> listeners = new ArrayList<>();
    
    public void addOrderListener(OrderListener listener) {
        listeners.add(listener);
    }
    
    public void removeOrderListener(OrderListener listener) {
        listeners.remove(listener);
    }
    
    public void createOrder(String orderNo) {
        System.out.println("创建订单: " + orderNo);
        
        // 触发事件
        OrderEvent event = new OrderEvent(this, orderNo);
        for (OrderListener listener : listeners) {
            listener.onOrderCreated(event);
        }
    }
}

// 具体监听器
class EmailNotifier implements OrderListener {
    @Override
    public void onOrderCreated(OrderEvent event) {
        System.out.println("发送邮件通知: 订单" + event.getOrderNo() + "已创建");
    }
}

class SMSNotifier implements OrderListener {
    @Override
    public void onOrderCreated(OrderEvent event) {
        System.out.println("发送短信通知: 订单" + event.getOrderNo() + "已创建");
    }
}

// 使用
public class EventListenerDemo {
    public static void main(String[] args) {
        OrderService orderService = new OrderService();
        
        orderService.addOrderListener(new EmailNotifier());
        orderService.addOrderListener(new SMSNotifier());
        
        orderService.createOrder("ORDER001");
    }
}`
			},
			{
				point: 'Spring事件机制：ApplicationEvent和ApplicationListener，实现松耦合的事件驱动。',
				code: `import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

// 自定义事件
class UserRegisteredEvent extends ApplicationEvent {
    private String username;
    
    public UserRegisteredEvent(Object source, String username) {
        super(source);
        this.username = username;
    }
    
    public String getUsername() {
        return username;
    }
}

// 事件监听器1
@Component
class EmailListener implements ApplicationListener<UserRegisteredEvent> {
    @Override
    public void onApplicationEvent(UserRegisteredEvent event) {
        System.out.println("发送欢迎邮件给: " + event.getUsername());
    }
}

// 事件监听器2（使用@EventListener注解）
@Component
class CouponListener {
    @EventListener
    public void handleUserRegistered(UserRegisteredEvent event) {
        System.out.println("发放优惠券给: " + event.getUsername());
    }
}

// 事件发布者
@Service
class UserService {
    @Autowired
    private ApplicationEventPublisher eventPublisher;
    
    public void register(String username) {
        System.out.println("用户注册: " + username);
        
        // 发布事件
        UserRegisteredEvent event = new UserRegisteredEvent(this, username);
        eventPublisher.publishEvent(event);
    }
}`
			},
			{
				point: '观察者模式的优缺点：解耦合、支持广播，但可能导致循环调用和性能问题。',
				code: `// 观察者模式的问题示例

// 问题1：循环依赖
class CircularProblem {
    Subject subject1 = new Subject();
    Subject subject2 = new Subject();
    
    {
        subject1.attach(msg -> {
            System.out.println("Subject1收到: " + msg);
            subject2.notifyObservers("来自Subject1");  // 可能导致无限循环
        });
        
        subject2.attach(msg -> {
            System.out.println("Subject2收到: " + msg);
            subject1.notifyObservers("来自Subject2");  // 循环通知
        });
    }
}

// 问题2：内存泄漏（观察者未移除）
class MemoryLeakProblem {
    public void badExample() {
        Subject subject = new Subject();
        
        for (int i = 0; i < 10000; i++) {
            Observer observer = msg -> System.out.println(msg);
            subject.attach(observer);
            // 忘记detach，导致观察者累积
        }
    }
    
    public void goodExample() {
        Subject subject = new Subject();
        Observer observer = msg -> System.out.println(msg);
        
        try {
            subject.attach(observer);
            // 使用观察者
        } finally {
            subject.detach(observer);  // 及时移除
        }
    }
}

// 解决方案：弱引用观察者
class WeakRefSubject {
    private List<WeakReference<Observer>> observers = new ArrayList<>();
    
    public void attach(Observer observer) {
        observers.add(new WeakReference<>(observer));
    }
    
    public void notifyObservers(String message) {
        Iterator<WeakReference<Observer>> it = observers.iterator();
        while (it.hasNext()) {
            Observer observer = it.next().get();
            if (observer == null) {
                it.remove();  // 自动清理已回收的观察者
            } else {
                observer.update(message);
            }
        }
    }
}`
			}
		]
	},
	{
		id: 35,
		title: '策略模式',
		description: '定义一系列算法，将每个算法封装起来，使它们可以互相替换，让算法独立于使用它的客户端。',
		icon: '♟️',
		categoryId: 'pattern',
		categoryName: '设计模式',
		categoryIcon: '🎨',
		difficulty: '进阶',
		color: 'linear-gradient(135deg, #d299c2 0%, #fef9d7 100%)',
		headerBg: 'linear-gradient(135deg, #2c3e50 0%, #34495e 100%)',
		tagBg: 'linear-gradient(135deg, #16a085 0%, #1abc9c 100%)',
		tagColor: '#ffffff',
		difficultyBg: 'linear-gradient(135deg, #e74c3c 0%, #c0392b 100%)',
		keyPoints: [
			{
				point: '策略模式：定义策略接口，不同算法实现该接口，上下文类持有策略并动态切换。',
				code: `// 策略接口
interface PaymentStrategy {
    boolean pay(double amount);
}

// 具体策略1：支付宝
class AlipayStrategy implements PaymentStrategy {
    private String account;
    
    public AlipayStrategy(String account) {
        this.account = account;
    }
    
    @Override
    public boolean pay(double amount) {
        System.out.println("使用支付宝 " + account + " 支付 " + amount + " 元");
        return true;
    }
}

// 具体策略2：微信支付
class WeChatStrategy implements PaymentStrategy {
    private String openId;
    
    public WeChatStrategy(String openId) {
        this.openId = openId;
    }
    
    @Override
    public boolean pay(double amount) {
        System.out.println("使用微信 " + openId + " 支付 " + amount + " 元");
        return true;
    }
}

// 具体策略3：银行卡
class BankCardStrategy implements PaymentStrategy {
    private String cardNo;
    
    public BankCardStrategy(String cardNo) {
        this.cardNo = cardNo;
    }
    
    @Override
    public boolean pay(double amount) {
        System.out.println("使用银行卡 " + cardNo + " 支付 " + amount + " 元");
        return true;
    }
}

// 上下文类
class PaymentContext {
    private PaymentStrategy strategy;
    
    public void setStrategy(PaymentStrategy strategy) {
        this.strategy = strategy;
    }
    
    public boolean executePayment(double amount) {
        if (strategy == null) {
            throw new IllegalStateException("未设置支付策略");
        }
        return strategy.pay(amount);
    }
}

// 使用
public class StrategyDemo {
    public static void main(String[] args) {
        PaymentContext context = new PaymentContext();
        
        // 使用支付宝
        context.setStrategy(new AlipayStrategy("user@example.com"));
        context.executePayment(100.0);
        
        // 切换到微信
        context.setStrategy(new WeChatStrategy("wx123456"));
        context.executePayment(200.0);
    }
}`
			},
			{
				point: '策略模式消除if-else：将复杂的条件分支转换为多个策略类，提高代码可维护性。',
				code: `// ❌ 不好的设计：大量if-else
class BadDiscountCalculator {
    public double calculate(String memberType, double price) {
        if ("普通会员".equals(memberType)) {
            return price * 0.9;
        } else if ("银卡会员".equals(memberType)) {
            return price * 0.8;
        } else if ("金卡会员".equals(memberType)) {
            return price * 0.7;
        } else if ("钻石会员".equals(memberType)) {
            return price * 0.6;
        } else {
            return price;
        }
        // 新增会员类型需要修改这个方法
    }
}

// ✅ 好的设计：策略模式
interface DiscountStrategy {
    double calculate(double price);
}

class NormalMemberStrategy implements DiscountStrategy {
    @Override
    public double calculate(double price) {
        return price * 0.9;
    }
}

class SilverMemberStrategy implements DiscountStrategy {
    @Override
    public double calculate(double price) {
        return price * 0.8;
    }
}

class GoldMemberStrategy implements DiscountStrategy {
    @Override
    public double calculate(double price) {
        return price * 0.7;
    }
}

class DiamondMemberStrategy implements DiscountStrategy {
    @Override
    public double calculate(double price) {
        return price * 0.6;
    }
}

// 使用策略模式
class GoodDiscountCalculator {
    private DiscountStrategy strategy;
    
    public GoodDiscountCalculator(DiscountStrategy strategy) {
        this.strategy = strategy;
    }
    
    public double calculate(double price) {
        return strategy.calculate(price);
    }
    
    // 动态切换策略
    public void setStrategy(DiscountStrategy strategy) {
        this.strategy = strategy;
    }
}

// 使用
public class DiscountDemo {
    public static void main(String[] args) {
        double price = 1000.0;
        
        GoodDiscountCalculator calculator = 
            new GoodDiscountCalculator(new GoldMemberStrategy());
        System.out.println("金卡会员价格: " + calculator.calculate(price));
        
        // 切换策略
        calculator.setStrategy(new DiamondMemberStrategy());
        System.out.println("钻石会员价格: " + calculator.calculate(price));
    }
}`
			},
			{
				point: '策略模式与工厂模式结合：使用工厂创建策略，避免客户端直接依赖具体策略类。',
				code: `import java.util.HashMap;
import java.util.Map;

// 策略接口
interface SortStrategy {
    void sort(int[] arr);
}

// 具体策略
class BubbleSort implements SortStrategy {
    @Override
    public void sort(int[] arr) {
        System.out.println("使用冒泡排序");
        // 冒泡排序逻辑
    }
}

class QuickSort implements SortStrategy {
    @Override
    public void sort(int[] arr) {
        System.out.println("使用快速排序");
        // 快速排序逻辑
    }
}

class MergeSort implements SortStrategy {
    @Override
    public void sort(int[] arr) {
        System.out.println("使用归并排序");
        // 归并排序逻辑
    }
}

// 策略工厂
class SortStrategyFactory {
    private static Map<String, SortStrategy> strategies = new HashMap<>();
    
    static {
        strategies.put("bubble", new BubbleSort());
        strategies.put("quick", new QuickSort());
        strategies.put("merge", new MergeSort());
    }
    
    public static SortStrategy getStrategy(String type) {
        SortStrategy strategy = strategies.get(type.toLowerCase());
        if (strategy == null) {
            throw new IllegalArgumentException("未知的排序策略: " + type);
        }
        return strategy;
    }
}

// 上下文类
class Sorter {
    public void sort(int[] arr, String strategyType) {
        SortStrategy strategy = SortStrategyFactory.getStrategy(strategyType);
        strategy.sort(arr);
    }
}

// 使用
public class FactoryStrategyDemo {
    public static void main(String[] args) {
        int[] arr = {5, 2, 8, 1, 9};
        Sorter sorter = new Sorter();
        
        sorter.sort(arr, "bubble");
        sorter.sort(arr, "quick");
        sorter.sort(arr, "merge");
    }
}`
			},
			{
				point: 'Java中的策略模式应用：Comparator接口、线程池的拒绝策略、Spring的Resource加载策略等。',
				code: `import java.util.*;

// 1. Comparator接口（策略模式）
public class ComparatorStrategyDemo {
    static class Student {
        String name;
        int age;
        
        public Student(String name, int age) {
            this.name = name;
            this.age = age;
        }
    }
    
    public static void main(String[] args) {
        List<Student> students = Arrays.asList(
            new Student("张三", 20),
            new Student("李四", 18),
            new Student("王五", 22)
        );
        
        // 策略1：按年龄排序
        students.sort(Comparator.comparingInt(s -> s.age));
        
        // 策略2：按姓名排序
        students.sort(Comparator.comparing(s -> s.name));
        
        // 策略3：自定义策略
        students.sort(new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                return s1.age - s2.age;
            }
        });
    }
}

// 2. 线程池拒绝策略
import java.util.concurrent.*;

public class ThreadPoolStrategyDemo {
    public static void main(String[] args) {
        // 不同的拒绝策略（都实现了RejectedExecutionHandler接口）
        
        // 策略1：AbortPolicy - 抛出异常
        ThreadPoolExecutor pool1 = new ThreadPoolExecutor(
            2, 4, 60, TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(2),
            new ThreadPoolExecutor.AbortPolicy()
        );
        
        // 策略2：CallerRunsPolicy - 调用者运行
        ThreadPoolExecutor pool2 = new ThreadPoolExecutor(
            2, 4, 60, TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(2),
            new ThreadPoolExecutor.CallerRunsPolicy()
        );
        
        // 策略3：DiscardPolicy - 直接丢弃
        ThreadPoolExecutor pool3 = new ThreadPoolExecutor(
            2, 4, 60, TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(2),
            new ThreadPoolExecutor.DiscardPolicy()
        );
        
        // 策略4：DiscardOldestPolicy - 丢弃最老的任务
        ThreadPoolExecutor pool4 = new ThreadPoolExecutor(
            2, 4, 60, TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(2),
            new ThreadPoolExecutor.DiscardOldestPolicy()
        );
    }
}`
			},
			{
				point: '策略模式的优缺点：易扩展、消除条件语句，但增加类的数量，客户端需知道所有策略。',
				code: `// 策略模式的优缺点示例

// 优点1：易于扩展
// 新增VIP会员策略，无需修改现有代码
class VIPMemberStrategy implements DiscountStrategy {
    @Override
    public double calculate(double price) {
        return price * 0.5;  // 5折
    }
}

// 优点2：避免多重条件判断
// 之前：if-else 10个分支
// 现在：10个策略类

// 优点3：策略可复用
class PriceCalculator {
    public double calcWithDiscount(double price, DiscountStrategy strategy) {
        return strategy.calculate(price);
    }
}

// 缺点1：类数量增加
// 每个策略都是一个类，可能导致类爆炸
// 解决方案：使用Lambda简化
Map<String, DiscountStrategy> strategies = new HashMap<>();
strategies.put("normal", price -> price * 0.9);
strategies.put("silver", price -> price * 0.8);
strategies.put("gold", price -> price * 0.7);

// 缺点2：客户端需要了解所有策略
// 客户端需要知道有哪些策略可用
// 解决方案：结合工厂模式或枚举

enum MemberType {
    NORMAL(price -> price * 0.9),
    SILVER(price -> price * 0.8),
    GOLD(price -> price * 0.7);
    
    private final DiscountStrategy strategy;
    
    MemberType(DiscountStrategy strategy) {
        this.strategy = strategy;
    }
    
    public double calculate(double price) {
        return strategy.calculate(price);
    }
}

// 使用枚举简化
public class EnumStrategyDemo {
    public static void main(String[] args) {
        double price = 1000.0;
        
        double normalPrice = MemberType.NORMAL.calculate(price);
        double goldPrice = MemberType.GOLD.calculate(price);
        
        System.out.println("普通会员: " + normalPrice);
        System.out.println("金卡会员: " + goldPrice);
    }
}`
			}
		]
	},
	{
		id: 36,
		title: '装饰器模式',
		description: '动态地给对象添加额外的职责，是继承的替代方案，提供比继承更灵活的扩展方式。',
		icon: '🎀',
		categoryId: 'pattern',
		categoryName: '设计模式',
		categoryIcon: '🎨',
		difficulty: '进阶',
		color: 'linear-gradient(135deg, #fdcbf1 0%, #e6dee9 100%)',
		headerBg: 'linear-gradient(135deg, #2c3e50 0%, #34495e 100%)',
		tagBg: 'linear-gradient(135deg, #16a085 0%, #1abc9c 100%)',
		tagColor: '#ffffff',
		difficultyBg: 'linear-gradient(135deg, #e74c3c 0%, #c0392b 100%)',
		keyPoints: [
			{
				point: '装饰器模式：组件接口+具体组件+装饰器抽象类+具体装饰器，动态添加功能。',
				code: `// 组件接口
interface Beverage {
    String getDescription();
    double cost();
}

// 具体组件（基本饮料）
class Coffee implements Beverage {
    @Override
    public String getDescription() {
        return "咖啡";
    }
    
    @Override
    public double cost() {
        return 10.0;
    }
}

class Tea implements Beverage {
    @Override
    public String getDescription() {
        return "茶";
    }
    
    @Override
    public double cost() {
        return 8.0;
    }
}

// 装饰器抽象类
abstract class CondimentDecorator implements Beverage {
    protected Beverage beverage;
    
    public CondimentDecorator(Beverage beverage) {
        this.beverage = beverage;
    }
}

// 具体装饰器1：牛奶
class Milk extends CondimentDecorator {
    public Milk(Beverage beverage) {
        super(beverage);
    }
    
    @Override
    public String getDescription() {
        return beverage.getDescription() + " + 牛奶";
    }
    
    @Override
    public double cost() {
        return beverage.cost() + 2.0;
    }
}

// 具体装饰器2：糖
class Sugar extends CondimentDecorator {
    public Sugar(Beverage beverage) {
        super(beverage);
    }
    
    @Override
    public String getDescription() {
        return beverage.getDescription() + " + 糖";
    }
    
    @Override
    public double cost() {
        return beverage.cost() + 1.0;
    }
}

// 具体装饰器3：摩卡
class Mocha extends CondimentDecorator {
    public Mocha(Beverage beverage) {
        super(beverage);
    }
    
    @Override
    public String getDescription() {
        return beverage.getDescription() + " + 摩卡";
    }
    
    @Override
    public double cost() {
        return beverage.cost() + 3.0;
    }
}

// 使用
public class DecoratorDemo {
    public static void main(String[] args) {
        // 基本咖啡
        Beverage beverage1 = new Coffee();
        System.out.println(beverage1.getDescription() + " $" + beverage1.cost());
        
        // 咖啡 + 牛奶
        Beverage beverage2 = new Milk(new Coffee());
        System.out.println(beverage2.getDescription() + " $" + beverage2.cost());
        
        // 咖啡 + 牛奶 + 糖 + 摩卡
        Beverage beverage3 = new Mocha(new Sugar(new Milk(new Coffee())));
        System.out.println(beverage3.getDescription() + " $" + beverage3.cost());
        // 输出：咖啡 + 牛奶 + 糖 + 摩卡 $16.0
    }
}`
			},
			{
				point: 'Java IO流的装饰器模式：InputStream、Reader等都使用装饰器模式层层包装功能。',
				code: `import java.io.*;

// Java IO流装饰器示例
public class IODecoratorDemo {
    public static void main(String[] args) throws IOException {
        // 最基本的文件输入流
        FileInputStream fis = new FileInputStream("file.txt");
        
        // 添加缓冲功能
        BufferedInputStream bis = new BufferedInputStream(fis);
        
        // 添加数据类型读取功能
        DataInputStream dis = new DataInputStream(bis);
        
        // 一次性包装
        DataInputStream stream = new DataInputStream(
            new BufferedInputStream(
                new FileInputStream("file.txt")
            )
        );
        
        // 类似地，输出流也是层层装饰
        DataOutputStream out = new DataOutputStream(
            new BufferedOutputStream(
                new FileOutputStream("output.txt")
            )
        );
        
        out.writeInt(123);
        out.writeUTF("Hello");
        out.close();
    }
}

/*
IO流装饰器结构：

InputStream (抽象组件)
├── FileInputStream (具体组件)
├── ByteArrayInputStream (具体组件)
└── FilterInputStream (装饰器抽象类)
    ├── BufferedInputStream (具体装饰器 - 添加缓冲)
    ├── DataInputStream (具体装饰器 - 添加数据类型读取)
    └── PushbackInputStream (具体装饰器 - 添加回推功能)

每一层都实现了InputStream接口，可以层层包装
*/

// 自定义装饰器示例
class LowerCaseInputStream extends FilterInputStream {
    public LowerCaseInputStream(InputStream in) {
        super(in);
    }
    
    @Override
    public int read() throws IOException {
        int c = super.read();
        return (c == -1 ? c : Character.toLowerCase((char) c));
    }
    
    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        int result = super.read(b, off, len);
        for (int i = off; i < off + result; i++) {
            b[i] = (byte) Character.toLowerCase((char) b[i]);
        }
        return result;
    }
}

// 使用自定义装饰器
InputStream in = new LowerCaseInputStream(
    new BufferedInputStream(
        new FileInputStream("test.txt")
    )
);`
			},
			{
				point: '装饰器vs继承：装饰器动态组合，继承静态固定；装饰器更灵活，避免类爆炸。',
				code: `// ❌ 不好的设计：使用继承
// 咖啡 + 不同配料的组合，会导致类爆炸

class CoffeeWithMilk extends Coffee {
    // 咖啡 + 牛奶
}

class CoffeeWithSugar extends Coffee {
    // 咖啡 + 糖
}

class CoffeeWithMilkAndSugar extends Coffee {
    // 咖啡 + 牛奶 + 糖
}

class CoffeeWithMilkAndMocha extends Coffee {
    // 咖啡 + 牛奶 + 摩卡
}

// 如果有n种配料，需要2^n个类！

// ✅ 好的设计：使用装饰器
// 3种配料，只需要3个装饰器类
// 可以自由组合：
Beverage b1 = new Milk(new Coffee());
Beverage b2 = new Sugar(new Coffee());
Beverage b3 = new Sugar(new Milk(new Coffee()));
Beverage b4 = new Mocha(new Sugar(new Milk(new Coffee())));

// 装饰器vs继承对比：
/*
继承：
- 编译时确定
- 静态扩展
- 子类与父类紧耦合
- 类爆炸问题
- 所有子类共享扩展

装饰器：
- 运行时确定
- 动态扩展
- 低耦合
- 灵活组合
- 针对对象扩展
*/

// 示例：动态添加功能
public class DynamicDecorator {
    public static Beverage customize(Beverage base, String[] options) {
        Beverage result = base;
        
        for (String option : options) {
            switch (option) {
                case "milk":
                    result = new Milk(result);
                    break;
                case "sugar":
                    result = new Sugar(result);
                    break;
                case "mocha":
                    result = new Mocha(result);
                    break;
            }
        }
        
        return result;
    }
    
    public static void main(String[] args) {
        // 用户自定义配置
        String[] options = {"milk", "sugar", "mocha"};
        Beverage beverage = customize(new Coffee(), options);
        
        System.out.println(beverage.getDescription());
        System.out.println("价格: $" + beverage.cost());
    }
}`
			},
			{
				point: '装饰器模式应用场景：动态添加功能、增强现有对象、需要大量子类组合的情况。',
				code: `// 应用场景1：日志装饰器
interface DataSource {
    void writeData(String data);
    String readData();
}

class FileDataSource implements DataSource {
    private String filename;
    
    public FileDataSource(String filename) {
        this.filename = filename;
    }
    
    @Override
    public void writeData(String data) {
        System.out.println("写入文件: " + data);
    }
    
    @Override
    public String readData() {
        return "文件数据";
    }
}

// 加密装饰器
class EncryptionDecorator implements DataSource {
    private DataSource source;
    
    public EncryptionDecorator(DataSource source) {
        this.source = source;
    }
    
    @Override
    public void writeData(String data) {
        String encrypted = encrypt(data);
        source.writeData(encrypted);
    }
    
    @Override
    public String readData() {
        String data = source.readData();
        return decrypt(data);
    }
    
    private String encrypt(String data) {
        return "加密(" + data + ")";
    }
    
    private String decrypt(String data) {
        return data.replace("加密(", "").replace(")", "");
    }
}

// 压缩装饰器
class CompressionDecorator implements DataSource {
    private DataSource source;
    
    public CompressionDecorator(DataSource source) {
        this.source = source;
    }
    
    @Override
    public void writeData(String data) {
        String compressed = compress(data);
        source.writeData(compressed);
    }
    
    @Override
    public String readData() {
        String data = source.readData();
        return decompress(data);
    }
    
    private String compress(String data) {
        return "压缩(" + data + ")";
    }
    
    private String decompress(String data) {
        return data.replace("压缩(", "").replace(")", "");
    }
}

// 使用
public class DataSourceDemo {
    public static void main(String[] args) {
        // 基本文件操作
        DataSource source1 = new FileDataSource("data.txt");
        source1.writeData("Hello");
        
        // 文件 + 加密
        DataSource source2 = new EncryptionDecorator(
            new FileDataSource("secure.txt")
        );
        source2.writeData("Secret");
        
        // 文件 + 加密 + 压缩
        DataSource source3 = new CompressionDecorator(
            new EncryptionDecorator(
                new FileDataSource("compressed.txt")
            )
        );
        source3.writeData("Important Data");
        // 写入流程：压缩 -> 加密 -> 文件
        // 读取流程：文件 -> 解密 -> 解压
    }
}`
			},
			{
				point: '装饰器模式注意事项：装饰器顺序影响结果、避免过度装饰、保持接口一致性。',
				code: `// 注意事项示例

// 1. 装饰器顺序很重要
public class DecoratorOrderDemo {
    public static void main(String[] args) {
        DataSource source1 = new CompressionDecorator(
            new EncryptionDecorator(new FileDataSource("file1.txt"))
        );
        // 写入：加密 -> 压缩 -> 文件
        // 读取：文件 -> 解压 -> 解密
        
        DataSource source2 = new EncryptionDecorator(
            new CompressionDecorator(new FileDataSource("file2.txt"))
        );
        // 写入：压缩 -> 加密 -> 文件
        // 读取：文件 -> 解密 -> 解压
        
        // 顺序不同，处理流程不同！
    }
}

// 2. 避免过度装饰
DataSource bad = new LogDecorator(
    new CacheDecorator(
        new ValidateDecorator(
            new EncryptionDecorator(
                new CompressionDecorator(
                    new BufferDecorator(
                        new FileDataSource("file.txt")
                    )
                )
            )
        )
    )
);  // 层次太深，难以维护

// 3. 保持接口一致性
interface TextComponent {
    String getText();
}

// ❌ 错误：装饰器添加了新方法
class BadDecorator implements TextComponent {
    private TextComponent component;
    
    public BadDecorator(TextComponent component) {
        this.component = component;
    }
    
    @Override
    public String getText() {
        return component.getText();
    }
    
    // ❌ 新增方法，破坏了装饰器模式
    public void newMethod() {
        // ...
    }
}

// ✅ 正确：只增强现有方法
class GoodDecorator implements TextComponent {
    private TextComponent component;
    
    public GoodDecorator(TextComponent component) {
        this.component = component;
    }
    
    @Override
    public String getText() {
        return "<b>" + component.getText() + "</b>";  // 增强现有方法
    }
}

// 4. 使用Builder简化装饰器组合
class DataSourceBuilder {
    private DataSource source;
    
    public DataSourceBuilder(String filename) {
        this.source = new FileDataSource(filename);
    }
    
    public DataSourceBuilder withEncryption() {
        this.source = new EncryptionDecorator(source);
        return this;
    }
    
    public DataSourceBuilder withCompression() {
        this.source = new CompressionDecorator(source);
        return this;
    }
    
    public DataSource build() {
        return source;
    }
}

// 使用Builder
DataSource source = new DataSourceBuilder("data.txt")
    .withEncryption()
    .withCompression()
    .build();`
			}
		]
	}
];